const fs = require("fs");
const path = require("path");

/**
 * @param {string} directoryPath
 * @param {string} fileName
 * @param {string} content
 */
function writeStringToFile(directoryPath, fileName, content) {
  if (!fs.existsSync(directoryPath)) {
    fs.mkdirSync(directoryPath, { recursive: true });
  }

  const filePath = path.join(directoryPath, fileName);

  fs.writeFileSync(filePath, content);

  console.log(`文件已成功写入：${filePath}`);
}

function copyFolderSync(source, target) {
  if (!fs.existsSync(target)) {
    fs.mkdirSync(target);
  }

  const files = fs.readdirSync(source);

  for (let file of files) {
    const current = fs.lstatSync(path.join(source, file));
    if (current.isDirectory()) {
      copyFolderSync(path.join(source, file), path.join(target, file));
    } else {
      fs.copyFileSync(path.join(source, file), path.join(target, file));
    }
  }
}

/**
 * 确保文件夹存在
 * @param {string} folderPath 
 */
function createFolderIfNotExists(folderPath) {
  if (!fs.existsSync(folderPath)) {
    fs.mkdirSync(folderPath);
    console.log("文件夹已创建");
  } else {
    console.log("文件夹已经存在");
  }
}

/**
 * 将蓝河 ux 转换为蓝河工程
 * @param {string} uxCode 蓝河代码
 * @param {string} targetPath 指定生成目录
 */
module.exports.exportCodeAsProject = (uxCode, targetPath) => {
  const filePath = path.join(process.cwd(), "./codeTemplate/src/pages/Demo/");
  const fileName = "index.ux";
  // 将 ux 文件写入模板项目
  writeStringToFile(filePath, fileName, uxCode);
  createFolderIfNotExists(targetPath);
  // 将项目拷贝到指定目录
  copyFolderSync(path.join(process.cwd(), "./codeTemplate"), targetPath);
};
